{% load static %}
<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <title>用户管理</title>
  <link rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <style>
        /* ===== 新增背景设置 ===== */
    body {
      font-family:"Segoe UI",sans-serif;
      margin:0;
      min-height:100vh;
      /* 背景图片设置 */
      background: url('{% static "images/background.jpg" %}') no-repeat center center fixed;
      background-size: cover;
      position: relative;
    }
    .wrapper    {max-width:960px;margin:40px auto;background:#fff;padding:24px 32px;
                 border-radius:16px;box-shadow:0 6px 18px rgba(0,0,0,.12)}
    h1          {margin:0 0 24px;color:#2563eb;display:flex;align-items:center;font-size:26px}
    h1 i        {margin-right:10px}
    table.user-table {width:100%;border-collapse:collapse;margin-bottom:32px;}
    table.user-table th, table.user-table td {
      padding:12px;text-align:center;border-bottom:1px solid #e5e7eb;
    }
    table.user-table th {
      background:#2563eb;color:#fff;font-weight:500;
    }
    .action-buttons button {
      margin:0 4px;padding:6px 12px;border:none;border-radius:6px;
      color:#fff;cursor:pointer;font-size:14px;
    }
    .action-buttons .edit-btn   {background:#10b981}
    .action-buttons .delete-btn {background:#ef4444}
    /* 弹窗 */
    .overlay {
      position:fixed;top:0;left:0;width:100vw;height:100vh;
      background:rgba(0,0,0,.4);display:none;z-index:9;
    }
    .popup {
      position:fixed;
      top:50%;left:50%;
      transform:translate(-50%,-50%);
      background:#fff;
      padding:24px;
      border-radius:12px;box-shadow:0 6px 20px rgba(0,0,0,.15);
      width:360px;
      display:none;z-index:10;
      text-align: left;
    }
    .popup h3 {
      margin: 0 0 20px;
      color:#2563eb;
      font-size:20px;
      text-align: left;}
    .popup input, .popup select {
      width:100%;padding:8px;border:1px solid #d1d5db;border-radius:6px;
      margin-bottom:16px;
      outline:none;
    }
    /* 复选框组整体左对齐，垂直方向排布 */
    .popup .check-group{
      display:flex;
      flex-direction:column;
      align-items:flex-start;   /* 整体左对齐 */
      gap:12px;                 /* 两行之间的间距 */
      margin-bottom:24px;       /* 与下面按钮留空 */
    }

    .popup label{
      display:flex;
      align-items:center;
      gap:8px;
      margin-bottom:0;          /* 行间距交给 .check-group 控制 */
      font-size:14px;
      justify-content:flex-start;  /* 关键：让内容靠左 */
    }

    /* 防止中文被自动拆行 */
    .popup label span{ white-space:nowrap; }

    .popup .edit-btn {
      width:100%;padding:10px;background:#2563eb;border:none;
      border-radius:6px;color:#fff;font-size:16px;cursor:pointer;
    }
    /* 底部导航 */
    .nav {
      margin:40px 0;            /* 上下留空以分离表格 */
      display:flex;
      gap:12px;
      justify-content:center;    /* 中心对齐 */
    }
    .nav a {
      display:flex;align-items:center;gap:6px;
      padding:8px 16px;border-radius:8px;text-decoration:none;
      color:#fff;font-size:14px;
    }
    .nav .devices  {background:#10b981}
    .nav .control  {background:#2563eb}
    .nav .messages {background:#f59e0b}
    .nav .logout   {background:#ef4444}
    .nav a:hover   {opacity:.9}
  </style>
</head>
<body>
<div class="wrapper">
  <h1><i class="fas fa-users-cog"></i>用户管理</h1>

  <table class="user-table">
    <thead>
      <tr>
        <th>用户名</th>
        <th>邮箱</th>
        <th>手机号</th>
        <th>注册时间</th>
        <th>角色</th>
        <th>查看权限</th>
        <th>控制权限</th>
        <th>操作</th>
      </tr>
    </thead>
    <tbody id="user-table-body">
      <!-- JS 动态渲染 -->
    </tbody>
  </table>
</div>

<div class="overlay" onclick="closePopup()"></div>
<div class="popup" id="popup-form">
  <h3 id="popup-title">编辑用户权限</h3>
  <input type="text" id="form-username" placeholder="用户名" disabled>
  <input type="email" id="form-email" placeholder="邮箱" disabled>
  <input type="tel"   id="form-phone" placeholder="手机号" disabled>
  <div class="check-group">
    <label><input type="checkbox" id="form-view"><span>查看权限</span></label>
    <label><input type="checkbox" id="form-control"><span>控制权限</span></label>
  </div>
  <button class="edit-btn" onclick="submitForm()">提交修改</button>
</div>

<!-- 底部导航 -->
<div class="nav">
  <a href="/device_manage/"  class="devices"><i class="fas fa-tools"></i>设备管理</a>
  <a href="/index/"          class="control"><i class="fas fa-sliders-h"></i>控制首页</a>
  <a href="/monitor/messages/" class="messages"><i class="fas fa-envelope"></i>监控</a>
  <a href="#"                class="logout" id="logoutBtn"><i class="fas fa-sign-out-alt"></i>登出</a>
</div>

<script>
  // —— 通用 fetch ——
  async function apiFetch(path, options={}) {
    const headers = {'Content-Type':'application/json','Accept':'application/json', ...(options.headers||{})};
    const res = await fetch(path, {...options, headers});
    const text = await res.text();
    let data = {};
    try{ data = text?JSON.parse(text):{} }catch{}
    if(!res.ok) throw new Error(data.detail||data.message||res.statusText);
    return data;
  }

  // —— 全局变量 ——
  let userList = [], editingId = null;

  document.addEventListener('DOMContentLoaded', loadUsers);

  // 拉取并渲染
  async function loadUsers(){
    try {
      userList = await apiFetch('/users/all/');
      renderTable();
    } catch(e) {
      alert('获取用户列表失败：'+e.message);
    }
  }

  function renderTable(){
    const tbody = document.getElementById('user-table-body');
    tbody.innerHTML = '';
    userList.forEach(u => {
      tbody.insertAdjacentHTML('beforeend', `
        <tr>
          <td>${u.username}</td>
          <td>${u.email||'—'}</td>
          <td>${u.phone||'—'}</td>
          <td>${u.reg_time||'—'}</td>
          <td>${u.role}</td>
          <td>${u.permission_level>=1?'✅':'❌'}</td>
          <td>${u.permission_level>=2?'✅':'❌'}</td>
          <td class="action-buttons">
            ${u.role==='管理员'
              ? '—'
              : `<button class="edit-btn" onclick="openEdit(${u.user_id})">编辑</button>
                 <button class="delete-btn" onclick="deleteUser(${u.user_id})">删除</button>`
            }
          </td>
        </tr>`);
    });
  }

  // 删除
  async function deleteUser(id){
    if(!confirm('确认删除此用户？')) return;
    try {
      await apiFetch(`/users/${id}/delete/`, {method:'DELETE'});
      userList = userList.filter(u=>u.user_id!==id);
      renderTable();
    } catch(e){
      alert('删除失败：'+e.message);
    }
  }

  // 打开弹窗
  function openEdit(id){
    editingId = id;
    const u = userList.find(x=>x.user_id===id);
    document.getElementById('form-username').value = u.username;
    document.getElementById('form-email').value    = u.email||'';
    document.getElementById('form-phone').value    = u.phone||'';
    document.getElementById('form-view').checked   = u.permission_level>=1;
    document.getElementById('form-control').checked= u.permission_level>=2;
    // “控制”权限依赖“查看”权限
    const v=document.getElementById('form-view'), c=document.getElementById('form-control');
    c.disabled = !v.checked;
    v.onchange = ()=>{
      if(!v.checked) c.checked=false;
      c.disabled = !v.checked;
    };
    document.querySelector('.overlay').style.display='block';
    document.getElementById('popup-form').style.display='block';
  }

  // 提交修改
  async function submitForm(){
    const view = document.getElementById('form-view').checked;
    const ctrl = document.getElementById('form-control').checked;
    if(ctrl && !view){
      return alert('请先授予查看权限');
    }
    const level = ctrl?2:(view?1:0);
    try {
      await apiFetch(`/users/${editingId}/update/`, {
        method:'PUT',
        body: JSON.stringify({permission_level:level})
      });
      userList.forEach(u=>{ if(u.user_id===editingId) u.permission_level=level });
      closePopup();
      renderTable();
    } catch(e){
      alert('更新失败：'+e.message);
    }
  }

  function closePopup(){
    document.querySelector('.overlay').style.display='none';
    document.getElementById('popup-form').style.display='none';
  }

  // —— 底部导航功能 ——
  document.getElementById('logoutBtn').addEventListener('click', e=>{
    e.preventDefault();
    localStorage.clear();
    window.location.href = '/';
  });
</script>
</body>
</html>